﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Blog.Models;
using BlogModel;

namespace Blog.Data
{
    public class CommentRepository
    {
        public static List<CommentModel> GetCommentsByPostId(int postId)
        {
            var comments =
                from c in DB.Context.CommentSet
                where c.PostId == postId && !c.IsDeleted
                select new CommentModel
                {
                    CommentId = c.CommentId,
                    CommentText = c.CommentText,
                    Email = c.Email,
                    CreationDate = c.CreationDate,
                    Name = c.Name,
                    PostId = c.PostId
                };

            return comments.ToList();
        }

        public static CommentModel GetCommentById(int id)
        {
            var comment = DB.Context.CommentSet
                .FirstOrDefault(c => c.CommentId == id && !c.IsDeleted);

            if (comment == null)
                return null;

            return new CommentModel
                {
                    CommentId = comment.CommentId,
                    CommentText = comment.CommentText,
                    CreationDate = comment.CreationDate,
                    Email = comment.Email,
                    Name = comment.Name,
                    PostId = comment.PostId
                };
        }

        public static int DeleteComment(int id)
        {
            var comment = DB.Context.CommentSet
                .FirstOrDefault(c => c.CommentId == id);

            if (comment != null)
                comment.IsDeleted = true;

            return DB.Context.SaveChanges();
        }

        public static int AddComment(CommentModel commentModel)
        {
            var comment = new Comment
            {
                Name = commentModel.Name,
                Email = commentModel.Email,
                CommentText = commentModel.CommentText,
                CreationDate = commentModel.CreationDate,
                PostId = commentModel.PostId
            };

            DB.Context.CommentSet.Add(comment);
            return DB.Context.SaveChanges();
        }
    }
}
